#!/usr/bin/env python
"""
面试系统启动脚本
"""

import os
import sys
import subprocess
import webbrowser
import time

def check_dependencies():
    """检查依赖是否安装"""
    print("检查依赖...")
    
    required_packages = [
        'django',
        'djangorestframework',
        'django-cors-headers',
        'chromadb',
        'python-docx'
    ]
    
    missing_packages = []
    
    for package in required_packages:
        try:
            __import__(package.replace('-', '_'))
        except ImportError:
            missing_packages.append(package)
    
    if missing_packages:
        print(f"缺少以下依赖包: {', '.join(missing_packages)}")
        print("请运行: pip install -r requirements.txt")
        return False
    
    print("依赖检查完成！")
    return True

def run_migrations():
    """运行数据库迁移"""
    print("运行数据库迁移...")
    try:
        subprocess.run([sys.executable, 'manage.py', 'makemigrations'], check=True)
        subprocess.run([sys.executable, 'manage.py', 'migrate'], check=True)
        print("数据库迁移完成！")
        return True
    except subprocess.CalledProcessError as e:
        print(f"数据库迁移失败: {e}")
        return False

def start_server():
    """启动Django服务器"""
    print("启动Django服务器...")
    print("服务器地址: http://localhost:8000")
    print("API地址: http://localhost:8000/api/interview/")
    print("前端地址: file://" + os.path.abspath("frontend/index.html"))
    print("\n按 Ctrl+C 停止服务器")
    
    try:
        # 延迟打开浏览器
        def open_browser():
            time.sleep(3)
            webbrowser.open('file://' + os.path.abspath("frontend/index.html"))
        
        import threading
        browser_thread = threading.Thread(target=open_browser)
        browser_thread.daemon = True
        browser_thread.start()
        
        # 启动Django服务器
        subprocess.run([sys.executable, 'manage.py', 'runserver'])
        
    except KeyboardInterrupt:
        print("\n服务器已停止")
    except Exception as e:
        print(f"启动服务器失败: {e}")

def main():
    """主函数"""
    print("=== 模拟面试系统启动器 ===\n")
    
    # 检查依赖
    if not check_dependencies():
        return
    
    # 运行迁移
    if not run_migrations():
        return
    
    print("\n=== 系统准备就绪 ===")
    print("1. 确保MySQL数据库正在运行")
    print("2. 检查数据库配置是否正确")
    print("3. 如需创建超级用户，请运行: python manage.py createsuperuser")
    print()
    
    # 启动服务器
    start_server()

if __name__ == '__main__':
    main()



